//package xmlTranslators;
package cpre556.project2.eclipsePlugin.support;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;

public class SourceReader{
	private String sourceFilename;
	private FileInputStream fis = null;
	private BufferedReader reader = null;
	
	private Saver saver;
	
	/**
	 * Constructor
	 * @param fn
	 * @deprecated Use SourceReader(Saver) instead
	 */
	public SourceReader(String fn){
		sourceFilename = fn;
	}
	
	/**
	 * Instantiates a new source reader.
	 * 
	 * @param s the s
	 */
	public SourceReader(Saver s){
		saver = s;
		
		sourceFilename = saver.getSource();
	}
	
	public String getLineOfCode(int ln){
		String lineOfCode = null;
		
		try{
			fis = new FileInputStream(sourceFilename);
			reader = new BufferedReader(new InputStreamReader(fis));
			
			for(int i = 1; i <= ln; i++){
				lineOfCode = reader.readLine();
			}
		}
		catch(FileNotFoundException fnfe){
			System.err.println("File not found:" + sourceFilename + ".");
		}
		catch(IOException ioe){
			System.err.println("I/O error:" + ioe);
		}
		
		return lineOfCode;
	}
	
	private Vector<String> toVector(String str){
		int strLength = str.length();
		Vector<String> returnVector = new Vector<String>();
		
		for(int i = 0; i<strLength; i++){
			returnVector.add(i, str.substring(i,i+1));
		}
		
		return returnVector;
	}
	
	public Vector<String> getXMLSafeLineOfCode(int ln){
		String loc = getLineOfCode(ln);
		
		Vector<String> charXMLData = toVector(loc);
		Vector<String> escapedXMLData = new Vector<String>();
		
		int count = 0;
		
		for(int i=0; i < charXMLData.size(); i++){
			if(charXMLData.get(i).toString().equalsIgnoreCase("&")){
				escapedXMLData.add(count,"&");
				count++;
				escapedXMLData.add(count,"a");
				count++;
				escapedXMLData.add(count,"m");
				count++;
				escapedXMLData.add(count,"p");
				count++;
				escapedXMLData.add(count,";");
				count++;
			}
			else if(charXMLData.get(i).toString().equalsIgnoreCase("<")){
				escapedXMLData.add(count,"&");
				count++;
				escapedXMLData.add(count,"l");
				count++;
				escapedXMLData.add(count,"t");
				count++;
				escapedXMLData.add(count,";");
				count++;
			}
			else if(charXMLData.get(i).toString().equalsIgnoreCase(">")){
				escapedXMLData.add(count,"&");
				count++;
				escapedXMLData.add(count,"g");
				count++;
				escapedXMLData.add(count,"t");
				count++;
				escapedXMLData.add(count,";");
				count++;
			}
			else{
				escapedXMLData.add(count,charXMLData.get(i));
				count++;
			}
		}
		return escapedXMLData;
	}
}
